package com.itstyle.quartz.service.impl;

import com.itstyle.quartz.dynamicquery.DynamicQuery;
import com.itstyle.quartz.entity.PageBean;
import com.itstyle.quartz.entity.Result;
import com.itstyle.quartz.entity.SignInLog;
import com.itstyle.quartz.service.ISignInLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service("SignInLogImpl")
public class SignInLogImpl implements ISignInLogService {

    @Autowired
    private DynamicQuery dynamicQuery;

    @Override
    @Transactional(readOnly = true)
    public Result listSignInLog(SignInLog signInLog, Integer pageNo, Integer pageSize) {
        String countSql = "SELECT COUNT(*) FROM signinlog";
        Long totalCount = dynamicQuery.nativeQueryCount(countSql);
        PageBean<SignInLog> data = new PageBean<>();
        if (totalCount > 0) {
            StringBuffer nativeSql = new StringBuffer();
            nativeSql.append("SELECT * FROM signinlog ");
            Object[] params = new Object[]{};
            if (!StringUtils.isEmpty(signInLog.getUsername())) {
                nativeSql.append("WHERE username = ?");
                params = new Object[]{signInLog.getUsername()};
            }
            nativeSql.append(" order by logId desc");
            Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
            List<SignInLog> list = dynamicQuery.nativeQueryPagingList(SignInLog.class, pageable, nativeSql.toString(), params);
            data = new PageBean<>(list, totalCount);
        }
        return Result.ok(data);
    }

    @Override
    @Transactional
    public Result delete(SignInLog signInLog) {
        dynamicQuery.delete(SignInLog.class, signInLog.getLogId());
        return Result.ok();
    }

    @Override
    @Transactional
    public void save(SignInLog signInLog) {
        dynamicQuery.save(signInLog);
    }
}
